< previous page page_557 next page >

Page 557
Passing String Parameters
The ByVal keyword tells Visual Basic to convert its String data type into a string that a C language function can read. This format is essentially a character array with a Null terminator on the end of the string. Therefore, Visual Basic reads its pointer, goes to that area of memory where the string is located, and passes the memory address of where the string is located to the function in the DLL. Because most of the Windows API is written in C, youll most likely always see the ByVal keyword present before any string parameter in a Declare statement.
As mentioned earlier, a Visual Basic strings base address is not actually where the string is located. Instead, its a certain amount of bytes that Visual Basic uses internally to determine where the string is located, the size of the string, and other information. If you attempt to pass this data to a C language program, the C language program would simply use whatever data was in these bytes instead of looking at the actual string. The only time you would pass a parameter without the ByVal keyword is if the C language function were written for use with the Visual Basic language.
If you forget the ByVal keyword, and the C language function is going to put some data into the string, the C language routine will overwrite memory thats reserved for Visual Basic plus anything else that happens to be located next to it in memory. This is one of the most common causes of fatal application errors.
Another problem with passing strings to a C language function can occur when the Visual Basic string is not allocated enough space to hold whatever data the C language function is going to put into the string. If you dim a string variable, Visual Basic does not set aside any space for this string other than the bytes it needs to manage the variable. The C language does not handle strings dynamically like Visual Basic does. It simply uses character arrays and pointers to add characters to this array. The C language will point to the base address of a character array and then start adding characters to the array until its done. If the character array is not allocated to enough elements to handle all the data, the C language just continues to write information into the adjacent memory space. It does not care that there may already be other data in that space. Because this is the case, you need to make sure you allocate enough space to the Visual Basic string prior to passing it to the C language function that will put characters into the string. Take the following code fragment, for example:
9f31265bb40b592b1929e18a47ab28e5.gif
Declare Sub ConvertString _
       Lib "MyLib.dll" (strString As String) As String

Dim strName As String

 
< previous page page_557 next page >

If you like this book, buy it!